package com.testt;

import java.net.InetAddress;

import com.test.R;


import android.app.Activity;
import android.app.AlertDialog;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;

public class TestConnectionT extends Activity {
    /** Called when the activity is first created. */
	EditText hostEditText, portEditText;
	TextView connectState;
	Button connectControlButton;
	Thread socketThread;
	Connection connection;
	
	enum ConnectionState { CLOSED, OPENING, OPENED };
	
	ConnectionState state = ConnectionState.CLOSED;
	
	@Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        hostEditText = (EditText)findViewById(R.id.hostView);
        portEditText = (EditText)findViewById(R.id.portView);
        connectState = (TextView)findViewById(R.id.connectState);
        connectState.setText(R.string.not_connected);
        connectControlButton = (Button)findViewById(R.id.connectControl);
        
        socketThread = new Thread(connection = new Connection(this));
        socketThread.start();
        
    }
    

	@Override
	protected void onDestroy() {
		super.onDestroy();
		connection.stop();
		try {
			socketThread.join();
		} catch (Exception ex) {
			reportException(ex);
		}
		
	}


	public void connectControl(View view)
    {
    	String hostString = hostEditText.getText().toString();
    	String portString = portEditText.getText().toString();
    	InetAddress serverAddress;
    	int dstPort;
    	
    	
    	
    	switch (state) {
    	case CLOSED:
	    	try {
	    		dstPort = Integer.parseInt(portString);
	    		serverAddress = InetAddress.getByName(hostString);
	            connectState.setText(R.string.connecting);
	            connectControlButton.setText(R.string.cancel);
	            connection.open(serverAddress, dstPort);
	            state = ConnectionState.OPENING;
	    	} catch (Exception ex) {
	            connectControlButton.setEnabled(true);
	    		connectState.setText(R.string.not_connected);
	    		reportException(ex);
	    		return;
	    	}
	    	break;
    	case OPENING:
    	case OPENED:
   			connection.close();
    		break;
    	}
    }
	
	void setConnected()
	{
		state = ConnectionState.OPENED;
		connectControlButton.setText(R.string.disconnect);
		connectState.setText(R.string.connected);
	}

	void setDisconnected()
	{
		state = ConnectionState.CLOSED;
		connectControlButton.setText(R.string.connect);
		connectState.setText(R.string.not_connected);
	}
 
	void reportException(Exception ex) {
		AlertDialog.Builder builder = new AlertDialog.Builder(this);
		builder.setMessage("socket failed " + ex + ex.getMessage());
		AlertDialog alert = builder.create();
		alert.show();
		
	}
}